import axios from 'axios'
import { ElMessage } from 'element-plus'

// Create axios instance
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Request interceptor
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// Response interceptor
api.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          ElMessage.error('登录已过期，请重新登录')
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          window.location.href = '/login'
          break
        case 403:
          ElMessage.error('没有权限访问')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error(error.response.data.message || '请求失败')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    return Promise.reject(error)
  }
)

// API functions
export const login = (data) => {
  return api.post('/auth/login', data)
}

export const getUserInfo = () => {
  return api.get('/auth/userinfo')
}

export const getUserPermissions = () => {
  return api.get('/auth/permissions')
}

// User management APIs
export const getAllUsers = () => {
  return api.get('/users')
}

export const getUserList = (params) => {
  return api.get('/users', { params })
}

export const getUserById = (id) => {
  return api.get(`/users/${id}`)
}

export const createUser = (data) => {
  return api.post('/users', data)
}

export const updateUser = (id, data) => {
  return api.put(`/users/${id}`, data)
}

export const deleteUser = (id) => {
  return api.delete(`/users/${id}`)
}

// Dictionary management APIs
export const getDictionaryList = (params) => {
  return api.get('/dictionary', { params })
}

export const getDictionaryById = (id) => {
  return api.get(`/dictionary/${id}`)
}

// Menu management APIs
export const getMenuList = () => {
  return api.get('/system/menu/list')
}

export const getMenuTree = () => {
  return api.get('/system/menu/tree')
}

export const getMenuTreeByRoleId = (roleId) => {
  return api.get(`/system/menu/tree/${roleId}`)
}

export const getMenuById = (id) => {
  return api.get(`/system/menu/${id}`)
}

export const addMenu = (data) => {
  return api.post('/system/menu', data)
}

export const updateMenu = (data) => {
  return api.put('/system/menu', data)
}

export const deleteMenu = (id) => {
  return api.delete(`/system/menu/${id}`)
}

export const deleteMenuBatch = (ids) => {
  return api.delete(`/system/menu/batch/${ids}`)
}

// Role management APIs
export const getAllRoles = () => {
  return api.get('/system/role/list')
}

export const getRoleById = (id) => {
  return api.get(`/system/role/${id}`)
}

export const addRole = (data) => {
  return api.post('/system/role', data)
}

export const updateRole = (data) => {
  return api.put('/system/role', data)
}

export const deleteRole = (id) => {
  return api.delete(`/system/role/${id}`)
}

export const deleteRoleBatch = (ids) => {
  return api.delete(`/system/role/batch/${ids}`)
}

export const assignMenus = (roleId, menuIds) => {
  return api.post(`/system/role/${roleId}/menus`, menuIds)
}

// User-Role management APIs
export const getRolesByUserId = (userId) => {
  return api.get(`/users/${userId}/roles`)
}

export const assignRolesToUser = (userId, roleIds) => {
  return api.post(`/users/${userId}/roles`, roleIds)
}

export const getDictionaryByType = (dictType) => {
  return api.get(`/dictionary/type/${dictType}`)
}

export const createDictionary = (data) => {
  return api.post('/dictionary', data)
}

export const updateDictionary = (id, data) => {
  return api.put(`/dictionary/${id}`, data)
}

export const deleteDictionary = (id) => {
  return api.delete(`/dictionary/${id}`)
}

// Dictionary import/export APIs
export const exportDictionary = () => {
  return api.get('/dictionary/export', { responseType: 'blob' })
}

export const importDictionary = (file) => {
  const formData = new FormData()
  formData.append('file', file)
  return api.post('/dictionary/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// Customer management APIs
export const getCustomerList = (params) => {
  return api.get('/customers', { params })
}

export const getCustomerById = (id) => {
  return api.get(`/customers/${id}`)
}

export const createCustomer = (data) => {
  return api.post('/customers', data)
}

export const updateCustomer = (id, data) => {
  return api.put(`/customers/${id}`, data)
}

export const deleteCustomer = (id) => {
  return api.delete(`/customers/${id}`)
}

export const getCustomerStatusOptions = () => {
  return api.get('/customers/status-options')
}

// Interaction Record management APIs
export const getInteractionRecordList = (params) => {
  return api.get('/interaction-records', { params })
}

export const getInteractionRecordById = (id) => {
  return api.get(`/interaction-records/${id}`)
}

export const createInteractionRecord = (data) => {
  return api.post('/interaction-records', data)
}

export const updateInteractionRecord = (id, data) => {
  return api.put(`/interaction-records/${id}`, data)
}

export const deleteInteractionRecord = (id) => {
  return api.delete(`/interaction-records/${id}`)
}

export const getInteractionRecordCustomers = () => {
  return api.get('/customers/by-creator')
}

export const getInteractionTypeOptions = () => {
  return api.get('/interaction-records/interaction-types')
}

export const getInteractionRecordsByCustomer = (customerId) => {
  return api.get(`/interaction-records/by-customer/${customerId}`)
}

// Analysis management APIs
export const getAnalysisAlerts = () => {
  return api.get('/analysis/alerts')
}

export const getCustomerTrendData = () => {
  return api.get('/analysis/customer-trend')
}

export const getHighValueCustomers = (params) => {
  return api.get('/analysis/high-value-customers', { params })
}

export const exportHighValueCustomers = (params) => {
  return api.get('/analysis/high-value-customers/export', { params })
}

// Sequence management APIs
export const getSequenceConfigList = (params) => {
  return api.get('/sequence/config/list', { params })
}

export const getSequenceConfigById = (id) => {
  return api.get(`/sequence/config/${id}`)
}

export const createSequenceConfig = (data) => {
  return api.post('/sequence/config', data)
}

export const updateSequenceConfig = (id, data) => {
  return api.put(`/sequence/config/${id}`, data)
}

export const deleteSequenceConfig = (id) => {
  return api.delete(`/sequence/config/${id}`)
}

export const generateSequence = (code) => {
  return api.post('/sequence/generate', null, { params: { code } })
}

export default api